package com.cbtx.tablet.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat.getSystemService
import com.bumptech.glide.Glide
import com.cbtx.tablet.R
import com.cbtx.tablet.bean.ChangeAdvEvent
import com.cbtx.tablet.bean.ScreenSaverBean
import kotlinx.android.synthetic.main.sp_fragment_adv_video.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.Serializable

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/7 5:15 PM
 * desc   :
 */
class PlayActivity : AbsBaseActivity() {

    private var mMediaPlayer: MediaPlayer? = null
    private var mPosition = 0

    var currentPlayPath = ""
    var mBannerItemList: MutableList<ScreenSaverBean> = ArrayList()

    var bannerCount = 0
    var isSurfaceCreated = false

    override fun layoutId(): Int = R.layout.sp_fragment_adv_video

    override fun initView(savedInstanceState: Bundle?) {

        EventBus.getDefault().register(this)

        initVideo()

        val bannerItemList: ArrayList<ScreenSaverBean> =
            intent.getSerializableExtra("bannerItemList") as ArrayList<ScreenSaverBean>
        mBannerItemList.addAll(bannerItemList)
        mPosition = -1
        bannerCount = mBannerItemList.size
        checkData()
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun checkData() {
        mPosition++
        if (mBannerItemList.size <= 0) {
            return
        }
        if (mPosition >= bannerCount) {
            mPosition = 0
        }
        //判断是否只有一个广告资源，避免不必要的轮播

        val bannerItem = mBannerItemList[mPosition]
        if (bannerItem.fileType == "img") {
            mIvAdvCover.visibility = View.VISIBLE
            loadImageAdv(bannerItem.filePath!!)

        } else {
            mIvAdvCover.visibility = View.GONE
            currentPlayPath = bannerItem.filePath!!
            if (isSurfaceCreated) {
                play()
            }
        }
        return
    }

    val mainHandler = Handler()
    private fun loadImageAdv(path: String) {
        Glide.with(this).load(path).into(mIvAdvCover)
        if (bannerCount > 1) {
            mainHandler.postDelayed({
                checkData()
            }, 1000 * 10)
        }
    }

    /**
     * 播放视频
     */
    fun initVideo() {
        if (mMediaPlayer == null) {
            //实例化MediaPlayer对象
            mMediaPlayer = MediaPlayer()
            mSurfaceView!!.visibility = View.VISIBLE
            val mHardwareDecoder = false
            // 不维持自身缓冲区，直接显示
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && mHardwareDecoder) {
                mSurfaceView!!.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
            }
            mSurfaceView!!.holder.setKeepScreenOn(true) //保持屏幕常亮
            mSurfaceView!!.holder.addCallback(SurFaceCallback())
        }
    }

    /**
     * 向player中设置dispay，也就是SurfaceHolder。但此时有可能SurfaceView还没有创建成功，所以需要监听SurfaceView的创建事件
     */
    private inner class SurFaceCallback : SurfaceHolder.Callback {
        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}

        override fun surfaceCreated(holder: SurfaceHolder) {
            isSurfaceCreated = true
            if (mMediaPlayer == null) {
                return
            }

            play()

        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            if (mMediaPlayer == null) {
                return
            }
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.stop()
                mPosition = mMediaPlayer!!.currentPosition
            }
        }


    }

    private fun play() {
        if (TextUtils.isEmpty(currentPlayPath)) {
            return
        }
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = MediaPlayer()
            }
            //添加播放视频的路径与配置MediaPlayer
            mMediaPlayer!!.reset()
            //给mMediaPlayer添加预览的SurfaceHolder，将播放器和SurfaceView关联起来
            mMediaPlayer!!.setDisplay(mSurfaceView!!.holder)
            mMediaPlayer!!.setDataSource(currentPlayPath)
            // 缓冲
            mMediaPlayer!!.prepare()
            mMediaPlayer!!.setOnBufferingUpdateListener(BufferingUpdateListener())
            mMediaPlayer!!.setOnPreparedListener(PreparedListener())
            mMediaPlayer!!.setOnCompletionListener(CompletionListener())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 缓冲变化时回调
     */
    private inner class BufferingUpdateListener : MediaPlayer.OnBufferingUpdateListener {
        override fun onBufferingUpdate(mp: MediaPlayer, percent: Int) {}
    }

    /**
     * 准备完成回调
     * 只有当播放器准备好了之后才能够播放，所以播放的出发只能在触发了prepare之后
     */
    private inner class PreparedListener : MediaPlayer.OnPreparedListener {
        override fun onPrepared(mp: MediaPlayer) {
            mMediaPlayer!!.start()
            mMediaPlayer!!.seekTo(0)
        }
    }

    /**
     * 播放结束时回调
     */
    private inner class CompletionListener : MediaPlayer.OnCompletionListener {
        override fun onCompletion(mp: MediaPlayer) {
            //如果只有一个视频广告，则重复播放
            if (mBannerItemList.size == 1) {
                mMediaPlayer!!.start()
            } else {
                stopPlay()

                //播放下个广告
                checkData()
            }
        }
    }

    public override fun onDestroy() {
        //释放内存，MediaPlayer底层是运行C++的函数方法，不使用后必需释放内存
        super.onDestroy()
        mainHandler.removeCallbacksAndMessages(null)

        EventBus.getDefault().unregister(this)

        stopPlay()
    }

    private val screenWidth: Int
        private get() = (getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
            .width

    private val screenHeight: Int
        private get() = (getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
            .height

    fun stopPlay() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.pause()
                mPosition = mMediaPlayer!!.currentPosition
            }
            mMediaPlayer!!.release()
            mMediaPlayer = null
        }
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {

        finish()
        return super.onTouchEvent(event)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun changeAdv(event : ChangeAdvEvent?){

        mBannerItemList.clear()
        mBannerItemList.addAll(event?.bannerItemList!!)
        mPosition = -1
        bannerCount = mBannerItemList.size

        mainHandler.removeCallbacksAndMessages(null)
        stopPlay()

        checkData()
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public fun playActivityFinish(event: String) {
//        if ("PlayActivityFinish" == event) {
//            finish()
//        }
//    }

}